package com.strom.concurrent;

import com.google.common.base.Ticker;
import com.google.common.util.concurrent.RateLimiter;

import java.lang.ref.Reference;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RateLimiterDemo {


    public static void main(String[] args) throws Exception {

       // 每秒2张许可证
        final RateLimiter rateLimiter = RateLimiter.create(3.0); // rate is "2 permits per second"
        ExecutorService service = Executors.newFixedThreadPool(3);
        List<Runnable> task = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            task.add(() -> System.out.println(LocalTime.now()));
        }
        submitTasks(task, service, rateLimiter);
    }

    static void submitTasks(List<Runnable> tasks, Executor executor, RateLimiter rateLimiter) {
        for (Runnable task : tasks) {
            rateLimiter.acquire(); // may wait
            executor.execute(task);
        }
    }
}
